<meta name="viewport" content="width=device-width,initial-scale=1" />
<template>
    <div class="wrap" >
      <el-container>
        <el-header class="title-word" style="margin-top: 10px">创建订单</el-header>
        <el-main>
          <el-form ref="orderForm" :model="orderForm" :rules="rules"  label-width="120px" style="margin-left:20%;margin-right:20%">
            <el-form-item label="选择客户" prop="customerNo">
              <el-autocomplete
                class="inline-input"
                v-model="orderForm.customerNo"
                :fetch-suggestions="querySearch"
                placeholder="请输入客户编号"
                @select="handleSelect"
                style="width: 73%;margin-left: -27%">
              </el-autocomplete>
            </el-form-item>
            <el-form-item label="实际总额" prop="finaltotal" style="width: 100%;">
              <el-input v-model="orderForm.finaltotal" placeholder="请输入金额"  prop="finaltotal" @input="limitInput($event,'finaltotal','orderForm')"></el-input>
            </el-form-item>
            <el-form-item label="产品总数" prop="amount" style="width: 100%;">
              <el-input v-model="orderForm.amount" placeholder="请输入产品总数"  prop="amount" @input="limitInput($event,'amount','orderForm')"></el-input>
            </el-form-item>
            <el-form-item label="下单日期"  prop="orderTime" style="width: 100%;">
              <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="选择下单日期" v-model="orderForm.orderTime" style="width: 100%;" prop="orderTime"></el-date-picker>
            </el-form-item>
            <el-form-item label="交货日期"  prop="leadtime" style="width: 100%;">
              <el-date-picker type="date" value-format="yyyy-MM-dd" v-model="orderForm.leadtime" placeholder="选择交货日期" style="width: 100%;" prop="leadtime"></el-date-picker>
            </el-form-item>
            <el-form-item label="发票信息"  prop="invoiceInfo" style="width: 100%;">
              <el-input v-model="orderForm.invoiceInfo" placeholder="不填则为客户默认信息，若无需发票，须填写“无”"></el-input>
            </el-form-item>
            <el-form-item label="物流信息"  prop="Logisticinfo" style="width: 100%;">
              <el-input v-model="orderForm.Logisticinfo" placeholder="不填则为客户默认信息，若无物流信息，须填写“无”"></el-input>
            </el-form-item>
            <el-form-item label="订单备注"  prop="remarks" style="width: 100%;">
              <el-input v-model="orderForm.remarks" style="width: 100%;"></el-input>
            </el-form-item>

            <div class="divider"></div>
            <el-form-item>
              <el-button @click="addItem" type="primary">增加</el-button>
            </el-form-item>
            <el-form-item
              v-for="(dynamicItem, index) in orderForm.dynamicItem"
              :key="dynamicItem.key"
              class="add-item"
              style="width: 100%;">
              <el-row>
                <el-col :span="7">
                  <el-form-item
                    :label="'产品名 '+ (index+1)"
                    :prop="'dynamicItem.' + index + '.productNo'"
                    :rules="{required: true, message: '请选择产品', trigger: 'change'}">
                      <!-- <el-autocomplete
                        class="inline-input"
                        v-model="dynamicItem.productNo"
                        :fetch-suggestions="querySearchPro">
                      </el-autocomplete> -->
                      <el-select v-model="dynamicItem.productNo" filterable clearable placeholder="请选择">
                        <el-option
                          v-for="item in orderForm.cpstos"
                          :key="item.productNo"
                          :label="item.productName"
                          :value="item.productNo">
                        </el-option>
                      </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item
                    label="产品数量"
                    :prop="'dynamicItem.' + index + '.orderAmount'"
                    :rules="{required: true, message: '请输入产品数量', trigger: 'blur'}">
                    <el-input v-model="dynamicItem.orderAmount"  @input="limitInput_d($event,'orderAmount',index)">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item
                    label="总计数量"
                    :prop="'dynamicItem.' + index + '.amount'"
                    :rules="{required: true, message: '请输入总计数量', trigger: 'blur'}">
                    <el-input v-model="dynamicItem.amount" @input="limitInput_d($event,'amount',index)">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item
                    label="产品单价"
                    :prop="'dynamicItem.' + index + '.price'"
                    :rules="{required: true, message: '请输入产品单价', trigger: 'blur'}">
                    <el-input v-model="dynamicItem.price" @input="limitInput_d($event,'price',index)">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-form-item>
                    <i class="el-icon-delete" @click="deleteItem(dynamicItem,index)"></i>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
            <div class="divider"></div>

            <el-form-item>
              <el-button type="primary" @click="onSubmit('orderForm')">立即创建</el-button>
              <el-button  @click="goback">取消</el-button>
            </el-form-item>
          </el-form>
        </el-main>
      </el-container>

    </div>
</template>

<script>
    export default {
      name: "createorder",
      data() {
        return {
          dialogVisible: false,
          orderForm: {
            orderNo:'',
            customerNo: '',
            finaltotal:'',
            leadtime:'',
            orderTime:'',
            amount:'',
            remarks:'',
            invoiceInfo:'',
            Logisticinfo:'',
            orders:[],
            cpstos:[],
            dynamicItem: [{
              productNo:'',
              orderAmount:'',
              price:'',
              amount:'',
            }]
          },
          rules: {
            customerNo: [
              { required: true, message: '请输入客户编号', trigger: 'change' },
            ],
            finaltotal: [
              { required: true, message: '请输入金额', trigger: 'blur' },
            ],
            amount: [
              { required: true, message: '请输入产品总数', trigger: 'blur' },
            ],
            leadtime: [
              { required: true, message: '请选择交货时间', trigger: 'change' },
            ],
            orderTime: [
              { required:  true, message: '请选择下单时间', trigger: 'change' },
            ]
          }
        };
      },
      methods: {
        /**
         * @param {string} value - 输入的值
         * @param {string} name - 匹配的对象属性 [mkPrice | slPrice]
         */
        limitInput(value, name,formName) {
          this[formName][name] =
            ("" + value) // 第一步：转成字符串
              .replace(/[^\d^\.]+/g, "") // 第二步：把不是数字，不是小数点的过滤掉
              .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
              .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
              .match(/^\d*(\.?\d{0,2})/g)[0] || ""; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
        },
        limitInput_d(value, name,index) {
          this.orderForm.dynamicItem[index][name] =
            ("" + value) // 第一步：转成字符串
              .replace(/[^\d^\.]+/g, "") // 第二步：把不是数字，不是小数点的过滤掉
              .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
              .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
              .match(/^\d*(\.?\d{0,2})/g)[0] || ""; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
        },
        querySearch(queryString, cb) {
          var orders = this.orderForm.orders;
          for(let i of this.orderForm.orders){
            i.value = i.customerName + "---" + i.customerNo;
          }
          orders = this.orderForm.orders;
          var results = queryString ? orders.filter(this.createStateFilter(queryString)) : orders;
          cb(results);
        },
//根据输入的字段进行筛选
        createStateFilter(queryString) {
          return (state) => {
            return (state.value.toString().toLowerCase().indexOf(queryString.toLowerCase()) === 0);
          };
        },
        loadAll() {
          this.$http.get("/hnhyscms_ws/customers/getAllCustomers",{emulateJSON:true}).then(
            success=>{
              this.orderForm.orders=success.data
            })
          this.$http.get("/hnhyscms_ws/cpstorage/getAllProducts",{emulateJSON:true}).then(
            success=>{
              this.orderForm.cpstos=success.data
            })
        },
        handleSelect(item) {
          this.orderForm.customerNo=item.customerNo
        },
        onSubmit(orderForm) {
          this.$refs[orderForm].validate((valid) => {
            if (valid) {
              let params={
                "customerNo":this.orderForm.customerNo,
                "finaltotal":this.orderForm.finaltotal,
                "leadtime":this.orderForm.leadtime,
                "orderTime":this.orderForm.orderTime,
                "amount":this.orderForm.amount,
                "remark":this.orderForm.remarks,
                "invoiceInfo":this.orderForm.invoiceInfo,
                "Logisticinfo":this.orderForm.Logisticinfo
              }
              this.$http.post("/hnhyscms_ws/orders/addOrder",params,{emulateJSON:true}).then(
                success=>{
                 this.orderForm.orderNo=success.data.orderNo
                   for(let i in this.orderForm.dynamicItem)
                  {
                    let param={
                      "orderNo": this.orderForm.orderNo,
                      "productNo":this.orderForm.dynamicItem[i].productNo,
                      "orderAmount":this.orderForm.dynamicItem[i].orderAmount,
                      "amount":this.orderForm.dynamicItem[i].amount,
                      "price":this.orderForm.dynamicItem[i].price,
                    }
                    console.log(param)
                    console.log(this.orderForm.orderNo)
                    this.$http.post("/hnhyscms_ws/orderdetails/addOrderDetails",param, {emulateJSON: true}).then(
                      success => {}
                    )
                  };
                  this.$confirm('创建成功')
                    .then(_ => {
                      done();
                    })
                    .catch(_ => {});
                  this.$router.go(-1)
                }
              )
            } else {
              return false;
            }
          });
        },
        addItem () {
          this.orderForm.dynamicItem.push({
            productNo:'',
            orderAmount:'',
            amount:'',
            price:'',
            key: Date.now()
          })
        },
        deleteItem (item,index) {
          this.orderForm.dynamicItem.splice(index, 1)
        },
        goback(){
          this.$router.go(-1)
        }
      },
      mounted() {
        this.loadAll();
      }
    }
</script>

<style scoped>
  .title-word {
    font-size: 30px;
    line-height:50px;
  }
  .add-item{
    margin-left: -80px;
  }
  .wrap{
    position: relative;
    height:100%;
    width: 100%;
    background-size: cover;
  }
  .divider {
    position: relative;
    width: 100%;
    height: 1px;
    background-color: #5a5a5a;
    text-align: center;
    font-size: 16px;
    color:black;
  }
</style>
